package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    private static final String reason = "订单超时，自动取消";

    /**
     * 使用Spring Task定时处理超时未支付订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟触发一次
    public void processTimeOutOrder(){
        log.info("处理超时订单中......{}",LocalDateTime.now());
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);

        List<Orders> timeOutOrders =  orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,orderTime);
        if(timeOutOrders.size() > 0 && timeOutOrders != null){
            for(Orders order : timeOutOrders){
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(reason);
                orderMapper.update(order);
            }
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     *  使用Redis 延迟队列处理超时订单:
     *     用户下单 → 存入 Redis (15 分钟后超时)
     *     用户支付 → Redis 数据仍存在，但不会被取消任务影响
     *     15 分钟后未支付 → checkTimeoutOrders() 触发 修改数据库状态为 "已取消"
     *     任务执行完后，Redis 自动删除已处理订单
     */
//    @Scheduled(fixedRate = 600000) // 每 600 秒执行
//    public void checkTimeoutOrders() {
//        long now = Instant.now().getEpochSecond();
//
//        Set<String> expiredOrderStrings = redisTemplate.opsForZSet().rangeByScore("order_timeout_queue", 0, now);
//
//        if (expiredOrderStrings != null && !expiredOrderStrings.isEmpty()) {
//            // 转换 String -> Long
//            Set<Long> expiredOrders = expiredOrderStrings.stream()
//                    .map(Long::parseLong) // 确保转换为 Long
//                    .collect(Collectors.toSet());
//
//            for (Long orderId : expiredOrders) {
//                // 确保订单仍然是“未付款”状态
//                Orders order = orderMapper.getById(orderId);
//                if (order != null) {
//                    order.setStatus(Orders.CANCELLED);
//                    order.setCancelTime(LocalDateTime.now());
//                    order.setCancelReason(reason);
//                    orderMapper.update(order);
//                    System.out.println("订单 " + orderId + " 已超时取消");
//                }
//                // 从 Redis 中删除该订单
//                redisTemplate.opsForZSet().remove("order_timeout_queue", String.valueOf(orderId));
//            }
//        }


//        Set<Long> expiredOrders = redisTemplate.opsForZSet()
//                .rangeByScore("order_timeout_queue", 0, now)
//                .stream()
//                .map(Long::valueOf) // 转换 String 为 Long
//                .collect(Collectors.toSet());
//
//        if (expiredOrders != null && !expiredOrders.isEmpty()) {
//            for (Long orderId : expiredOrders) {
//                // 确保订单仍然是“未付款”状态
//                Orders order = orderMapper.getById(orderId);
//                if (order != null) {
//                    order.setStatus(Orders.CANCELLED);
//                    order.setCancelTime(LocalDateTime.now());
//                    order.setCancelReason(reason);
//                    orderMapper.update(order);
//                    System.out.println("订单 " + orderId + " 已超时取消");
//                }
//                // 从 Redis 中删除该订单
//                redisTemplate.opsForZSet().remove("order_timeout_queue", orderId);
//            }
//        }
//    }


    @Scheduled(cron = " 0 0 1 * * ?")//每天凌晨一点处理一直处于派送中的订单
    public void processDeliveryOrders() {
        log.info("定时处理处于派送中的订单：{}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);

        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders order : ordersList) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
